﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Highlighterr
{
    public partial class StatisticsForm : Form
    {
        private Intellisenser _Intellisenser = null;
        private StringBuilder _StringBuilder = new StringBuilder();
        private StringBuilder _ErrorStringBuilder = new StringBuilder();
        private Intellisenser.IntellisenserLogItemAdded _LogItemAddedHandler = null;

        public StatisticsForm()
        {
            InitializeComponent();
        }


        public void SetIntellisenser(Intellisenser i)
        {
            _Intellisenser = i;
            UpdateIntellisenserStats();

            foreach (string error in _Intellisenser.ErrorLog)
            {
                _ErrorStringBuilder.Append(error);
                _ErrorStringBuilder.Append("\r\n\r\n");
            }
            ErrorLogTextBox.Text = _ErrorStringBuilder.ToString();
            _LogItemAddedHandler = new Intellisenser.IntellisenserLogItemAdded(Intellisenser_OnLogItemAdded);
            _Intellisenser.OnLogItemAdded += _LogItemAddedHandler;
        }

        private void UpdateIntellisenserStats()
        {
            if (_Intellisenser != null)
            {
                _StringBuilder.Clear();
                _StringBuilder.AppendFormat("SDF: {0}, {1} words loaded", _Intellisenser.SDFFileName, _Intellisenser.TotalItemsInDictionary);
                SDFLabel.Text = _StringBuilder.ToString();

                _StringBuilder.Clear();
                _StringBuilder.AppendFormat("Words parsed: {0}", _Intellisenser.WordsParsed);
                WordsParsedLabel.Text = _StringBuilder.ToString();
            }
            else
            {
                SDFLabel.Text = "SDF: not loaded";
                WordsParsedLabel.Text = "Words parsed: 0";
            }
        }


        private void Intellisenser_OnLogItemAdded(string error)
        {
            _ErrorStringBuilder.Append(error);
            _ErrorStringBuilder.Append("\r\n\r\n");
            ErrorLogTextBox.Text = _ErrorStringBuilder.ToString();
        }

        private void UpdateTimer_Tick(object sender, EventArgs e)
        {
            UpdateIntellisenserStats();
        }

        private void AutoRefreshCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            UpdateTimer.Enabled = AutoRefreshCheckBox.Checked;
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            UpdateIntellisenserStats();
        }

        private void StatisticsForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_LogItemAddedHandler != null)
            {
                _Intellisenser.OnLogItemAdded -= _LogItemAddedHandler;
            }
        }

    }
}
